package com.yxy.ms.manager.web;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yxy.ms.manager.common.Common;
import com.yxy.ms.manager.common.Results;
import com.yxy.ms.manager.entity.po.JobDetail;
import com.yxy.ms.manager.entity.po.JobTrigger;
import com.yxy.ms.manager.service.JobService;

@RestController
@RequestMapping("/job")
public class JobController {
    private final static Logger LOGGER = LoggerFactory.getLogger(JobController.class);

    @Autowired
    private Scheduler scheduler;
    @Autowired
    private JobService jobService;

    @PostMapping("/list")
    public Results list(@RequestBody String data) {
        JSONObject root = JSON.parseObject(data);
        JSONObject page = root.getJSONObject("page");
        JSONObject params = root.getJSONObject("params");
        if (null != page) {
            PageHelper.startPage(null != page.getInteger("pageIndex") ? page.getInteger("pageIndex") : 1,
                null != page.getInteger("pageSize") ? page.getInteger("pageSize") : 10);
            PageHelper.orderBy(StringUtils.isEmpty(page.getString("orderBy")) ? "" : page.getString("orderBy"));
        }
        Page<JobDetail> list = jobService.listQuartzEntity(params);
        return Common.results200(getPageData(list));
    }

    @PostMapping("/findJobTriggers")
    public Results findJobTriggers(@RequestBody String data) {
        JSONObject root = JSON.parseObject(data);
        JSONObject page = root.getJSONObject("page");
        JSONObject params = root.getJSONObject("params");
        if (null != page) {
            PageHelper.startPage(null != page.getInteger("pageIndex") ? page.getInteger("pageIndex") : 1,
                null != page.getInteger("pageSize") ? page.getInteger("pageSize") : 10);
            PageHelper.orderBy(StringUtils.isEmpty(page.getString("orderBy")) ? "" : page.getString("orderBy"));
        }

        Page<JobTrigger> list = jobService.findJobTriggers(params);
        return Common.results200(getPageData(list));
    }

    // @SuppressWarnings({"unchecked", "rawtypes"})
    // @PostMapping("/add")
    // public Results save(@RequestBody String data) {
    // LOGGER.info("新增任务");
    // try {
    // com.yxy.ms.scheduler.clear.entity.po.JobDetail jobDetail =
    // JSON.parseObject(data, com.yxy.ms.scheduler.clear.entity.po.JobDetail.class);
    // // 获取Scheduler实例、废弃、使用自动注入的scheduler、否则spring的service将无法注入
    // // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
    // // 如果是修改 展示旧的 任务
    // if (jobDetail.getOldJobGroup() != null) {
    // JobKey key = new JobKey(jobDetail.getOldJobName(), jobDetail.getOldJobGroup());
    // scheduler.deleteJob(key);
    // }
    // Class cls = Class.forName(jobDetail.getJobClassName());
    // cls.newInstance();
    // // 构建job信息
    // JobDetail job = JobBuilder.newJob(cls).withIdentity(jobDetail.getJobName(), jobDetail.getJobGroup())
    // .withDescription(jobDetail.getDescription()).build();
    // // 触发时间点
    // CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(jobDetail.getCronExpression());
    // Trigger trigger =
    // TriggerBuilder.newTrigger().withIdentity("trigger" + jobDetail.getJobName(), jobDetail.getJobGroup())
    // .startNow().withSchedule(cronScheduleBuilder).build();
    // // 交由Scheduler安排触发
    // scheduler.scheduleJob(job, trigger);
    // } catch (Exception e) {
    // e.printStackTrace();
    // return Common.results400(e.getMessage());
    // }
    // return Common.results200();
    // }

    @PostMapping("/trigger")
    public Results trigger(@RequestBody String data) {
        try {
            JobDetail jobDetail = JSON.parseObject(data, JobDetail.class);
            JobKey key = new JobKey(jobDetail.getJobName(), jobDetail.getJobGroup());
            scheduler.triggerJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return Common.results400(e.getMessage());
        }
        return Common.results200();
    }

    @PostMapping("/pause")
    public Results pause(@RequestBody String data) {
        LOGGER.info("停止任务");
        try {
            JobDetail jobDetail = JSON.parseObject(data, JobDetail.class);
            JobKey key = new JobKey(jobDetail.getJobName(), jobDetail.getJobGroup());
            scheduler.pauseJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return Common.results400(e.getMessage());
        }
        return Common.results200();
    }

    @PostMapping("/resume")
    public Results resume(@RequestBody String data) {
        LOGGER.info("恢复任务");
        try {
            JobDetail jobDetail = JSON.parseObject(data, JobDetail.class);
            JobKey key = new JobKey(jobDetail.getJobName(), jobDetail.getJobGroup());
            scheduler.resumeJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return Common.results400(e.getMessage());
        }
        return Common.results200();
    }

    @PostMapping("/remove")
    public Results remove(@RequestBody String data) {
        try {
            JobDetail jobDetail = JSON.parseObject(data, JobDetail.class);
            TriggerKey triggerKey = TriggerKey.triggerKey(jobDetail.getJobName(), jobDetail.getJobGroup());
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            scheduler.deleteJob(JobKey.jobKey(jobDetail.getJobName(), jobDetail.getJobGroup()));

        } catch (Exception e) {
            e.printStackTrace();
            return Common.results400(e.getMessage());
        }
        return Common.results200();
    }

    @GetMapping("/loadShedNames")
    public Results getShedName() {
        return Common.results200(jobService.loadShedNames());
    }

    @GetMapping("/loadJobGrops")
    public Results getJobGrops() {
        return Common.results200(jobService.loadJobGrops());
    }

    @GetMapping("/loadJobStatus")
    public Results getJobStatus() {
        return Common.results200(jobService.loadJobStatus());
    }

    private Map<String, Object> getPageData(Page<?> page) {
        Map<String, Object> result = new HashMap<String, Object>();
        // 总记录数
        result.put("total", page.getTotal());
        // 总页数
        result.put("pages", page.getPages());
        // 每页记录数
        result.put("pageSize", page.getPageSize());
        // 当前页码
        result.put("pageNum", page.getPageNum());
        // 结果
        result.put("rows", page.getResult());
        return result;
    }
}
